package org.example.controller;

import com.github.pagehelper.PageInfo;
import org.example.entity.Tag;
import org.example.service.TagService;
import org.example.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 谢娅
 */
@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/tag")
public class TagController {

    @Resource
    private TagService tagService;

    @PostMapping("/save")
    public Map<String,Object> save(@RequestBody Tag tag) {
        if(tag.getName() == null || tag.getName().equals("")){
            return Result.fileMap("Tag name cannot be empty");
        }
        return Result.successMap("Tag saved successfully");
    }

    @DeleteMapping("/remove/{id}")
    public Map<String,Object> remove(@PathVariable Serializable id) {
        Tag tag = tagService.getById(id);
        if (tag == null){
            return Result.fileMap("Tag does not exist");
        }
        return Result.successMap("Tag removed successfully");
    }

    @PutMapping("/update")
    public Map<String,Object> update(@RequestBody Tag tag) {
        if(tag.getTagId() == null){
            return Result.fileMap("Tag id cannot be empty");
        }
        if(StringUtils.isEmpty(tag.getName())){
            return Result.fileMap("Tag name cannot be empty");
        }
        boolean b = tagService.updateById(tag);
        if(!b){
            return Result.successMap("Tag update failed");
        }
        return Result.successMap("Tag updated successfully");
    }

    @GetMapping("/list")
    public Map<String,Object> list() {
        Map<String,Object> map = new HashMap<>();
        map.put("tagList",new PageInfo<>(tagService.list()));
        return Result.successMap(map);
    }

    @GetMapping("/getInfo/{id}")
    public Map<String,Object> getInfo(@PathVariable Serializable id) {
        return Result.successMap(tagService.getById(id));
    }
}